package com.yesep.client;


import com.yesep.netty.NettyChannelManager;
import com.yesep.netty.NettyServerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * @program: gateway
 * @description: netty客户端
 * @author: quliang
 * @create: 2019-07-09 14:02
 **/
@Component
public class NettyClient {

    private static ChannelFuture future;

    public void start(String host, int port) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(new InetSocketAddress(host, port))
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(
                                    new NettyClientHandler()
                            );
                            ByteBuf delimiter = Unpooled.copiedBuffer("\r\n"
                                    .getBytes());
                            ch.pipeline().addLast(
                                    new IdleStateHandler(3600, 0, 0,
                                            TimeUnit.SECONDS)); // 链路空闲状态触发器
                            ch.pipeline().addLast(
                                    "frameDecoder",
                                    new DelimiterBasedFrameDecoder(2048,
                                            delimiter));
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast("encoder",
                                    new StringEncoder());
                            ch.pipeline().addLast(new NettyClientHandler());
                        }
                    });
            future = b.connect().sync();
            //启动成功
            if (future.isSuccess()) {
                System.out.println("启动完毕11");
//                this.upStreamDataThread.init();
//                this.downStreamDataThread.init();
//                logger.info("[GatewayServer]服务启动成功，端口号：" + this.port);
            }

            System.out.println("Clinet start listen at " + port);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public void send(String mn, Object msg) {
        try {
            Channel channelByMn = NettyChannelManager.getInstance().getChannelByMn(mn);
            System.out.println(channelByMn);
            channelByMn.writeAndFlush(msg);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
